<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles.css">
    <title>二维码生成器</title>
</head>

<style>

    .inputUrl{
        height: 50px;
        width: 60%;
        border-radius: 5px;
        border-color: black;
        font-size: 20px;
    }

    .btn{
        width: 20%;
        height: 50px;
        background: black;
        color: white;
        margin-left: 5px;
        border-radius: 5px;
        border: none;
        margin-top: 20px;
    }

    .context {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-top: 30px;
    }

</style>

<body>

    <div style="text-align: center">
        <h1>请输入url链接(必须以http:// 或者 https://开头 例如:https://www.baidu.com)</h1>
        <br/>

        <input class="inputUrl" type="text" id="qr-data" onchange="generateQR()">
        <br>
        <button class="btn" type="submit" id="qr_button" >生成二维码</button>
        <br>
        <button class="btn" onclick="downloadDivPng('qrcode')">下载二维码</button>

        <div class="context" id="qrcode"></div>

    </div>
    
</body>


<script src="qrcode.min.js"></script>
<script>
    var qrdata = document.getElementById('qr-data');
    var qrcode = new QRCode(document.getElementById('qrcode'));

    function generateQR(){
        var data = qrdata.value;
        qrcode.makeCode(data);
    }

    function downloadDivPng(qrcodeID) {
        var divElement = document.getElementById(qrcodeID);
        var canvas = document.createElement('canvas');
        canvas.width = divElement.offsetWidth;
        canvas.height = divElement.offsetHeight;
        var context = canvas.getContext('2d');
        
        setTimeout(function(){
            context.drawImage(document.getElementById(qrcodeID).firstChild, 0, 0);
            var imgURL = canvas.toDataURL('image/png');
            var link = document.createElement('a');
            link.download ='qr-code.png';
            link.href = imgURL;
            link.click();
        },  500);
    }
</script>

</html>